package com.slipper.system.codeless.service;

import java.util.List;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import com.slipper.system.codeless.bo.TemplateBO;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;

import com.slipper.system.codeless.dao.TemplateDao;

import com.slipper.core.transaction.ReadTransactional;
import com.slipper.core.transaction.WriteTransactional;
import com.slipper.util.Tool;
import com.slipper.util.UUID;

@Service
@ReadTransactional
public class TemplateService {
    @Resource
    private TemplateDao templateDao;
    
    public TemplateBO queryBy(String id) {
        return templateDao.queryBy(id);
    }
    
    public List<TemplateBO> queryList(TemplateBO bo) {
        return templateDao.queryList(bo);
    }
    
    public PageInfo<TemplateBO> queryPage(TemplateBO bo) {
        PageHelper.startPage(bo.getPageNumber(), bo.getPageSize());
        return new PageInfo<>(templateDao.queryList(bo));
    }
    
    @WriteTransactional
    public int save(TemplateBO bo) {
        if (Tool.isNotBlank(bo.getId())) {
            bo.setUpdateTime(System.currentTimeMillis());
            return templateDao.update(bo);
        } else {
            bo.setId(UUID.getUUID());
            bo.setUpdateTime(System.currentTimeMillis());
            bo.setCreateTime(System.currentTimeMillis());
            return templateDao.insert(bo);
        }
    }

    @WriteTransactional
    public void saveList(List<TemplateBO> templateList) {
        if (templateList == null) return;

        templateList.forEach(template -> {
            if (templateDao.queryBy(template.getId()) != null) {
                template.setUpdateTime(System.currentTimeMillis());
                templateDao.update(template);
            } else {
                template.setUpdateTime(System.currentTimeMillis());
                template.setCreateTime(System.currentTimeMillis());
                templateDao.insert(template);
            }
        });
    }
    
    @WriteTransactional
    public int delete(TemplateBO bo) {
        return templateDao.delete(bo);
    }
    
    public long queryTotal(TemplateBO bo) {
        PageHelper.startPage(0, 0);
        return new PageInfo<>(templateDao.queryList(bo)).getTotal();
    }

    public TemplateBO queryByName(String name) {
        return templateDao.queryByName(name);
    }
}
